<template>
  <el-card class="box-card" shadow="never">
    <div slot="header" class="clearfix">
      <!-- head-container1 历史 -->
      <div class="head-container-app-sole">
        <el-button v-if="currentPatient.highOxygenStates === 1" size="mini" type="primary" class="filter-item"
          @click="dialogVisible = true">
          知情同意
        </el-button>
        <el-button v-if="currentPatient.highOxygenStates === 1" size="mini" type="primary" class="filter-item"
          @click="jumpPage('/therapistsSite/operationDoctorAdvice')">
          操舱医嘱
        </el-button>
        <!-- <el-button size="mini" type="primary" class="filter-item"
          @click="jumpPage('/therapistsSite/highPressureOxygenCost')">
          费用
        </el-button> -->
        <el-button size="mini" type="primary" class="filter-item" @click="
          jumpPage(
            '/therapistsSite/historyAssess?id=' + activeRow.reservationId
          )
          ">
          历史评估
        </el-button>
        <el-button size="mini" type="primary" class="filter-item"
          @click="jumpPage('/therapistsSite/rehabilitationHistory')"
          v-if="currentPatient.dicItemCategoryName === '运动康复'">
          运动康复历史
        </el-button>
        <el-button size="mini" type="primary" class="filter-item"
          @click="jumpPage('/therapistsSite/highPressureOxygenHistory')" v-if="currentPatient.highOxygenStates === 1">
          高压氧治疗历史
        </el-button>
        <el-button size="mini" type="primary" class="filter-item" @click="toTherapistsExe">
          执行
        </el-button>
        <!-- <el-button size="mini" type="danger" class="filter-item" @click="cancelToTherapistsExe">
          取消执行
        </el-button> -->
      </div>
      <!-- head-container-2 记录-->
      <div class="head-container-app-sole">
        <!-- <div class="table_title">治疗结果</div> -->
        <div class="table_title">对治疗进行评估与记录：</div>
        <el-button size="mini" type="primary" plain class="filter-item"
          @click="jumpPage('/therapistsSite/psychologicalAssessment')" v-if="currentPatient.highOxygenStates === 1">
          心理评估
        </el-button>
        <el-button size="mini" type="primary" plain class="filter-item"
          @click="jumpPage('/therapistsSite/highPressureOxygenRecord')" v-if="currentPatient.highOxygenStates === 1">
          高压氧记录
        </el-button>
        <el-button size="mini" type="primary" plain class="filter-item"
          @click="jumpPage('/therapistsSite/rehabilitationRecord')"
          v-if="currentPatient.dicItemCategoryName === '运动康复'">
          运动康复记录
        </el-button>
        <!-- <el-button size="mini" type="primary" plain class="filter-item" @click="jumpPage('/assessClt/assess?id=' + activeRow.reservationId)"> -->
        <el-button size="mini" type="primary" plain class="filter-item"
          @click="jumpPage(`/assessClt/assess?id=${activeRow.reservationId}&adviceId=${activeRow.adviceId}`)">
          治疗评估
        </el-button>
      </div>
    </div>
    <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" hide-required-asterisk>
      <el-form-item label="姓名">
        <el-input v-model="currentPatient.patientName" disabled style="width: 90px" />
      </el-form-item>
      <el-form-item label="住院号/门诊号" disabled>
        <el-input :value="currentPatient.patientType === 1
          ? currentPatient.outpatientNum
          : currentPatient.patientType === 2
            ? currentPatient.admissionNum
            : currentPatient.outpatientNum || currentPatient.admissionNum
          " style="width: 100px" disabled />
      </el-form-item>
      <el-form-item label="就诊类型" disabled>
        <el-input :value="getLabel(currentPatient.patientType, PATIENT_TYPE_LIST)" disabled style="width: 90px" />
      </el-form-item>
      <el-form-item label="执行时间" prop="exeTime">
        <el-date-picker v-model="form.exeTime" type="datetime" placeholder="选择日期时间" style="width: 200px"
          value-format="timestamp" :clearable="false" />
      </el-form-item>
      <el-form-item label="实际执行次数" style="width: 180px">
        <el-input :value="`${currentPatient.exeNum || 0
          }`" disabled style="width: 50px" /></el-form-item>
      <el-form-item label="治疗项目">
        <el-input v-model="currentPatient.treatmentName" disabled />
      </el-form-item>
      <el-form-item label="治疗时长" prop="treatmentDuration">
        <el-input v-model="form.treatmentDuration" style="width: 120px">
          <template slot="append">分钟</template></el-input>
      </el-form-item>
      <el-form-item label="执行科室">
        <!-- <el-input
          v-model="currentPatient.departmentName"
          disabled
          style="width: 280px"
        /> -->
        <el-select v-model="form.exeDepartmentCode" class="filter-item" placeholder="请选择" style="width: 200px">
          <el-option v-for="item in options.departmentList" :key="item.departmentCode" :label="item.departmentName"
            :value="item.departmentCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="执行医生">
        <el-input v-model="form.exeDoctor" style="width: 120px" />
      </el-form-item>
      <el-form-item label="记录时间" prop="recordTime">
        <el-date-picker v-model="form.recordTime" type="datetime" placeholder="选择日期时间" style="width: 200px"
          :clearable="false" value-format="timestamp" />
      </el-form-item>
      <el-form-item label="治疗小结" prop="treatmentSummary" class="text_area_item">
        <el-input v-model="form.treatmentSummary" :autosize="{ minRows: 5 }" type="textarea" placeholder="点击标签可一键填充" />

        <el-tag v-for="tag in summaryTags" :key="tag.name" :type="tag.type" style="margin: 2px 5px 2px 0;"
          @click="summaryTagsClick($event)">{{ tag.name }}</el-tag>

      </el-form-item>
      <!-- <el-form-item label="治疗视频">
        <el-upload class="upload-demo" drag action="https://jsonplaceholder.typicode.com/posts/" multiple>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传--格式文件，且不超过---</div>
        </el-upload>
      </el-form-item> -->
    </el-form>
    <el-row style="text-align: right">
      <el-button type="primary" @click="submit('form')" :loading="submitLoading">
        保存
      </el-button>
    </el-row>
    <el-table ref="table" v-loading="crud.loading" :data="crud.data[crud.listName]" highlight-current-row>
      <el-table-column label="序号" width="60px" prop="indexNumber">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <!-- <el-table-column
        :show-overflow-tooltip="true"
        prop="index"
        label="序号"
      /> -->
      <el-table-column :show-overflow-tooltip="true" prop="reservationTime" label="预约时间">
        <template slot-scope="scope">
          {{
            scope.row.reservationTime
              ? moment(scope.row.reservationTime).format("YYYY-MM-DD HH:mm")
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="exeNum" label="实际执行" />
      <el-table-column :show-overflow-tooltip="true" prop="exeTime" label="执行时间">
        <template slot-scope="scope">
          {{
            scope.row.exeTime
              ? moment(scope.row.exeTime).format("YYYY-MM-DD HH:mm")
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="treatmentDuration" label="治疗时长（分钟）" />
      <el-table-column :show-overflow-tooltip="true" prop="exeDoctor" label="执行医生" />
      <el-table-column :show-overflow-tooltip="true" prop="recordDoctor" label="记录医生" />
      <el-table-column :show-overflow-tooltip="true" prop="recordTime" label="记录时间">
        <template slot-scope="scope">
          {{
            scope.row.recordTime
              ? moment(scope.row.recordTime).format("YYYY-MM-DD HH:mm:ss")
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="treatmentSummary" label="治疗小结" />
    </el-table>
    <pagination />
    <el-dialog title="知情同意书" :visible.sync="dialogVisible" width="60%">
      <informedConsent :patientInfo="currentPatient" :treatmentInformedInfo="treatmentInformedInfo" @close="close"
        :isSign="{}">
      </informedConsent>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">
          退 出
        </el-button>
      </div>
    </el-dialog>
  </el-card>
</template>
<script>
import { sendAdviceQuery, sendInfoQuery } from "@/api/outpatient/medicalAdvice";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import pagination from "@crud/Pagination";
import { getLabel, PATIENT_TYPE_LIST } from "../enums";
import Cookies from "js-cookie";
import moment from "moment";
import InformedConsent from "@/views/outpatient/treatmentBilling/InformedConsent";
import {
  therapistsResultAdd,
  therapistsExe,
} from "@/api/therapistsSite/therapistsSite";
import { Notification } from "element-ui";
const defaultTableForm = {};
const getTimestamp = () => {
  return moment().valueOf();
};
const defaultForm = {
  exeDoctor: "",
  exeTime: getTimestamp(),
  recordTime: getTimestamp(),
  treatmentSummary: "",
  treatmentDuration: "",
  exeDepartmentCode: undefined,
};

export default {
  name: "executionRight",
  components: { pagination, informedConsent: InformedConsent },
  cruds() {
    return CRUD({
      title: "治疗结果列表",
      url: "admin/therapists/result/list",
      optShow: {
        reset: false,
        add: false,
        edit: false,
        del: false,
        download: false,
        opts: false,
      },
      queryOnPresenterCreated: false,
      idField: "index",
      query: {
        reservationId: undefined,
      },
      props: {
        pageIndexKey: "page",
        pageSizeKey: "size",
      },
      treatmentInformedInfo: {
        //治疗知情同意书参数
        signName: "",
        treatmentTarget: [],
        dicPatientRelation: "",
        coreRisk: [],
        fingerprint: "",
        signTime: "",
      },
    });
  },
  mixins: [presenter(), header(), form(defaultTableForm), crud()],
  props: {
    activeRow: {
      type: Object,
      default: null,
    },
  },
  computed: {
    currentPatient() {
      this.getMedicalAdvice();
      return this.activeRow ? this.activeRow : {};
    },
  },
  data() {
    return {
      submitLoading: false,
      Cookies,
      PATIENT_TYPE_LIST,
      permission: {
        add: ["admin", "execution/add"],
        edit: ["admin", "execution/edit"],
        del: ["admin", "execution/delete"],
      },
      rules: {
        treatmentDuration: [
          { required: true, message: "请输入治疗时长", trigger: "blur" },
        ],
        treatmentSummary: [
          { required: true, message: "请输入治疗小结", trigger: "blur" },
        ],
      },
      currentRow: null,
      form: Object.assign({}, defaultForm),
      options: {
        departmentList: [],
      },
      //治疗小结tag
      summaryTags: [
        { name: '治疗过程顺利', type: '' },
        { name: '状态稳步提升', type: 'success' },
        { name: '状态有所改善', type: 'info' },
        { name: '还需继续治疗', type: 'warning' },
        { name: '清空', type: 'danger' },
      ],
      dialogVisible: false,
      treatmentInformedInfo: {
        //治疗知情同意书参数
        signName: "",
        treatmentTarget: [],
        dicPatientRelation: "",
        coreRisk: [],
        fingerprint: "",
        signTime: "",
      },
    };
  },
  watch: {
    activeRow: function (val, oldVal) {
      if (val) {
        this.crud.query.reservationId = val.reservationId;
        this.crud.toQuery();
        // console.log(val,"activeRow");
      }
    },
  },
  created() {
    const userInfo = this.$store.state.user.user;
    this.form.exeDoctor = userInfo.realname;
    const departmentList = userInfo.departmentList;
    if (Array.isArray(departmentList) && departmentList.length > 0) {
      this.options.departmentList = departmentList;
      this.form.exeDepartmentCode = departmentList[0].departmentCode;
    }
  },
  methods: {
    getLabel,
    moment,
    jumpPage(path, query) {
      this.$router.push({
        path,
        query,
      });
    },
    // 医嘱详情请求
    getMedicalAdvice() {
      console.log(this.activeRow, "this.activeRow");

      // sendAdviceQuery(this.batchId).then((res) => {
      // });
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          therapistsResultAdd({
            reservationId: this.currentPatient.reservationId,
            ...this.form,
          })
            .then(() => {
              this.$notify({
                title: "保存成功",
                type: "success",
                duration: 1500,
              });
              this.crud.toQuery();
              this.form = Object.assign(this.form, {
                exeTime: getTimestamp(),
                recordTime: getTimestamp(),
                treatmentSummary: "",
                treatmentDuration: "",
              });
            })
            .finally(() => {
              this.submitLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    cancelToTherapistsExe() {
      console.log("取消执行");
    },
    toTherapistsExe() {
      this.$confirm(`确认执行？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            therapistsExe({
              reservationId: this.currentPatient.reservationId,
            })
              .then((res) => {
                Notification.success({
                  title: res.msg,
                });
                this.$emit("refresh");
                done();
              })
              .catch((res) => { })
              .finally(() => {
                instance.confirmButtonLoading = false;
              });
          } else {
            done();
          }
        },
      })
        .then((res) => { })
        .catch((res) => { });
    },
    close(e) { },
    //治疗小结标签点击事件
    summaryTagsClick(event) {
      const tagName = event.target.textContent;
      if (tagName == '清空') {
        this.form.treatmentSummary = '';
      } else {
        this.form.treatmentSummary = tagName;
      };
    },
  },

  mounted() {
  }
};
</script>
<style lang="scss" scoped>
/deep/.crud-opts {
  display: inline-flex;
}

.table_title {
  display: inline-block;
  line-height: 30px;
  margin: 0 10px 0 0;
  vertical-align: middle;
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}

.head-container-app-sole {
  line-height: 30.5px;
  padding-bottom: 0;

  /deep/.filter-item {
    margin-bottom: 0;
  }
}

.text_area_item {
  width: 100%;

  /deep/.el-form-item__content {
    width: calc(100% - 80px);
  }
}
</style>
